package consumer

import (
	"encoding/json"
	"github.com/streadway/amqp"
	"go.uber.org/zap"
	"niu-video/app/consts"
	"niu-video/app/model"
	"niu-video/pkg/db"
	"niu-video/pkg/es"
	"strings"

	//"niu-video/pkg/es"
	"niu-video/pkg/logger"
	"niu-video/pkg/rabbitmq"
)

func registerVideoConsumer() {
	// 新建连接
	rabbit := rabbitmq.NewRabbitMQ(consts.RABBITMQ_VIDEO_EXCHANGE, consts.RABBITMQ_VIDEO_ROUTE, consts.RABBITMQ_VIDEO_QUEUE)
	// 执行消费
	rabbit.Consume(func(d amqp.Delivery) error {
		var videoMessage model.VideoMessage
		if err := json.Unmarshal(d.Body, &videoMessage); err != nil {
			logger.Info("rabbitmq", zap.String("rabbitmq", "json解析失败！"))
		}
		//写db 事务
		tx := db.DB.Begin()

		v := model.Video{
			UserID:     videoMessage.UserID,
			VideoURL:   videoMessage.VideoURL,
			CoverURL:   videoMessage.CoverURL,
			Title:      videoMessage.Title,
			Tags:       videoMessage.Tags,
			CategoryId: videoMessage.CategoryId,
		}
		tx.Create(&v)
		err := tx.Commit().Error
		if err != nil {
			logger.LogIf(err)
			tx.Rollback()
			return err
		}
		logger.Info("rabbitmq", zap.String("consumer", "消费 video"+v.VideoURL))
		// 插入es
		videoEs := model.VideoEs{
			VideoID:    v.VideoID,
			CoverURL:   v.CoverURL,
			UserID:     v.UserID,
			VideoURL:   v.VideoURL,
			Title:      v.Title,
			CategoryId: v.CategoryId,
			CreateTime: v.CreateTime,
			UpdateTime: v.UpdateTime,
			Tags:       strings.Split(v.Tags, " "),
		}
		err = es.ES.IndexDocument(consts.VIDOE_ES_INDEX, videoEs)
		if err != nil {
			logger.Error("es", zap.String("index", err.Error()))
		}
		return err
	})
}
